package com.lihan.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;
@Component
public class WebSocketServer {

    private static class SingletionWSServer {
        static final WebSocketServer instance = new WebSocketServer();
    }

    public static WebSocketServer getInstance() {
        return SingletionWSServer.instance;
    } //创建一个WebSocketServer单例

    private EventLoopGroup mainGroup; //线程处理连接
    private EventLoopGroup subGroup; //线程处理读写操作
    private ServerBootstrap bootstrap; //启动类，进行相关的配置
    private ChannelFuture future; //连接结果是否成功返回后的类


    public WebSocketServer() {
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        bootstrap = new ServerBootstrap();

        bootstrap.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class) //通道是nio类型
                .childHandler(new WSServerInitialzer());
    }

    public void start() {
        this.future = bootstrap.bind("0.0.0.0",8088); //异步监听连接端口8088
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("启动 Netty 成功");
                }
            }
        }); //添加一个监听类，判断是否启动成功
    }
}


